<template>
    <div id='goods_list'>
      <div class="search-box">
        <Row type="flex" align='middle' style="padding-top: 24px;">
          <Col style="width: 8px ;height: 20px;background: #2D8CF0;" class="search-item"></Col>
          <Col style="margin-left: 10px">
            <h3>{{this.$route.query.shopName}} - 零售商品</h3>
          </Col>
        </Row>
        <Row type="flex">
          <Row type="flex" justify="start" class="search-item-left">
            <Col class="search-item">
              <span class="search-label">商品标题：</span>
              <Input placeholder="请输入" v-model='searchName' :maxlength='20'></Input>
            </Col>
            <Col class="search-item" style="display: flex;align-items: center;">
              <span class="search-label">商品分类：</span>
              <!-- <Select v-model="saleType" @on-change="doSearch" style="width:180px" placeholder='请选择'>
                <Option v-for="item in saleList" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select> -->
              <vueTreeselectChoice :width="200"
                v-model="saleType"
                :disable-branch-nodes="true"
                @input="doSearch"
                :options="saleList"
                permissionCode='1'></vueTreeselectChoice>
            </Col>
            <Col class="search-item">
              <span class="search-label">上架状态：</span>
              <Select v-model="status" @on-change="doSearch" style="width:180px" placeholder='请选择'>
                <Option v-for="item in statusList" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </Col>
            <Col class="search-item">
              <Button class="search-btn" type='primary' @click="doSearch">查询</Button>
            </Col>
            <Col class="search-item">
              <Button class="search-btn" @click="reset">重置</Button>
            </Col>
          </Row>
          <Row type="flex" justify="end" class="search-item-right">
            <Col class="search-item">
              <Button class="search-btn" style="width: 120px" @click='displayDraw' v-if="hasPermission('moms:product:shopproductsortsetting')">显示排序设置</Button>
            </Col>
            <Col class="search-item">
              <Button type='primary' class="search-btn" @click='putaway' v-if="hasPermission('moms:product:shopproductupdate')">上架</Button>
            </Col>
          </Row>
          </Row>
        </Row>
      </div>
      <Table stripe class="table-list" :columns="columns" :data="tableData" :loading="loading" :height="tableHeight">
        <template slot-scope="{ row }" slot="imgUrl">
          <div>
            <img :src="row.thumbnail?row.thumbnail:defaultUrl" alt="" style="width: 90px;height: 60px;display: block;margin: 15px 0;">
          </div>
        </template>
        <template slot-scope="{ row }" slot="inventory">
          <span>{{row.inventory === -1 ? '不限制' : row.inventory}}</span>
        </template>
        <template slot-scope="{ row }" slot="goodsTypeName">
          <span>{{row.parentSysCategoryName}} - {{row.sysCategoryName}}</span>
        </template>
        <template slot-scope="{ row }" slot="standardPrice">
          <span v-if='row.goodsPrices.length>0'>{{row.goodsPrices[0].amount.toFixed(2)}}</span>
        </template>
        <template slot-scope="{ row }" slot="goodsStatus">
          <span>{{row.channelGoodsStatus === 1 ? '已上架' : (row.channelGoodsStatus === 0 || row.channelGoodsStatus === 2 ) ? '已下架': ''}}</span>
        </template>
        <template slot-scope="{ row }" slot="action">
          <i class="iconsys icondetail" title="查看" v-if="hasPermission('moms:product:shopproductdetail')" @click='skipDetail(row)'></i>
          <Poptip confirm title="确认下架吗？" transfer  style="text-align:left" @on-ok="sureDown(row)" @on-cancel="cancelDown(row)">
            <i class="iconsys iconxiajia" title="下架" v-if="row.channelGoodsStatus === 1"></i>
          </Poptip>
        </template>
      </Table>
      <Row type='flex' justify="end" style='padding: 20px'>
        <Col>
          <Page :total="pageObj.total"
                :page-size='pageObj.pageSize'
                :current='pageObj.pageIndex'
                :page-size-opts='[20,50,100,200]'
                show-total
                show-sizer
                @on-change='changePageIndex'
                @on-page-size-change='changePageSize' />
        </Col>
      </Row>
      <display-order v-model="drawShow" :value='drawShow' :transmit='transmit' @closeDraw='closeDraw' @sureSelect='sureSelect'></display-order>
    </div>
  </template>

<script>
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import DisplayOrder from '@/view/components/display-order/index.vue'
import { getGoodsList, getIsShow, getClassifyList } from '@/api/commondity/index'
import { mapState } from 'vuex'
export default {
  name: 'goods_list',
  components: { DisplayOrder, vueTreeselectChoice },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    }),
    tableHeight () {
      let height = this.tableData.length > 5 ? 520 : 0
      return height
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.shopId !== to.params.id) {
        vm.shopId = to.params.id
        vm.reset()
      } else {
        if (from.name === 'goods_putaway') {
          vm.shopId = to.params.id
          vm.transmit.shopId = to.params.id
          vm.getData()
        }
      }
    })
  },
  data () {
    return {
      shopId: '',
      transmit: {
        goodsKind: '03-0304',
        type: '1',
        shopId: this.$route.params.id
      },
      defaultUrl: require('@/assets/images/default.png'),
      loading: false,
      drawShow: false,
      status: '1',
      searchName: '',
      saleType: null,
      saleList: [],
      displayData: [],
      tableData: [],
      statusList: [
        { value: '1', label: '已上架' },
        { value: '2', label: '已下架' }
      ],
      pageObj: {
        searchName: '',
        total: 0,
        pageIndex: 1,
        pageSize: 20
      },
      columns: [
        {
          title: '商品主图',
          slot: 'imgUrl'
        },
        {
          title: '商品标题',
          key: 'title'
        },
        {
          title: '商品编码',
          key: 'skuId'
        },
        {
          title: '商品分类',
          slot: 'goodsTypeName'
        },
        {
          title: '平台价(元)',
          slot: 'standardPrice'
        },
        {
          title: '可售库存',
          slot: 'inventory'
        },
        {
          title: '上架时间',
          key: 'listingAt'
        },
        {
          title: '下架时间',
          key: 'delistingAt'
        },
        {
          title: '状态',
          slot: 'goodsStatus'
        },
        {
          title: '操作时间',
          key: 'operatedAt'
        },
        {
          title: '操作',
          slot: 'action'
        }
      ]
    }
  },
  methods: {
    doSearch () {
      this.pageObj.pageIndex = 1
      this.pageObj.searchName = this.searchName
      this.getData()
    },
    reset () {
      this.saleType = null
      this.status = '1'
      this.searchName = ''
      this.pageObj.searchName = ''
      this.pageObj.pageIndex = 1
      this.pageObj.pageSize = 20
      this.getData()
    },
    changePageIndex (index) {
      this.pageObj.pageIndex = index
      this.getData()
    },
    changePageSize (size) {
      this.pageObj.pageSize = size
      this.pageObj.pageIndex = 1
      this.getData()
    },
    displayDraw () {
      this.drawShow = true
    },
    closeDraw (data) {
      this.drawShow = data
    },
    onSure () {},
    onCancel () {},
    // againUp (row) {
    //   this.modalShow = true
    // },
    sureSelect (data) {
      if (data) {
        this.getData()
      }
    },
    putaway () {
      this.$router.push({ name: 'goods_putaway', query: { shopId: this.$route.params.id, shopName: this.$route.query.shopName } })
    },
    skipDetail (row) {
      this.$router.push({ name: 'goods_detail', params: { id: row.channelGoodsId } })
    },
    sureDown (row) {
      let data = {
        channelGoodsId: row.channelGoodsId,
        listingType: 2
      }
      this.getStatus(data)
    },
    // 获取商品分类
    getProductList () {
      function fliterItem (item) {
        if (!item) return null
        // item.id = item.categoryId
        item.id = item.sysCategoryId
        item.orgName = item.categoryName
        if (item.subCategoryList && item.subCategoryList.length) {
          item.childList = item.subCategoryList.map(ele => {
            let newImte = fliterItem(ele)
            return newImte
          })
        }
        return item
      }
      getClassifyList({
        merchantId: this.$store.state.user.merchantId,
        categoryType: 1
      }).then(res => {
        if (res.data.status === 200) {
          this.saleList = (res.data.data.categories || []).map(item => {
            let newImte = fliterItem(item)
            return newImte
          })
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    // 下架
    getStatus (data) {
      getIsShow({
        merchantId: this.merchantId,
        updater: this.userId,
        updaterName: this.userName,
        ...data
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('下架成功！')
          this.getData()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    getData () {
      this.loading = true
      getGoodsList({
        merchantId: this.$store.state.user.merchantId,
        categoryId: this.saleType,
        channelGoodsStatus: this.status,
        title: this.pageObj.searchName,
        shopId: this.$route.params.id,
        goodsKind: '03-0304',
        offset: this.pageObj.pageSize * (this.pageObj.pageIndex - 1),
        limit: this.pageObj.pageSize,
        sortBy: 'sortNo'
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.tableData = result.data.goods || []
          this.pageObj.total = result.data.total
          if (result.data.goods.length / this.pageObj.pageSize === 0) {
            if (this.pageObj.pageIndex > 1) {
              this.pageObj.pageIndex--
              this.getData()
            }
          }
          if (this.tableData.length > 0) {
            this.tableData.forEach(ele => {
              ele.goodsTypeName = []
              ele.isShow = !!Number(ele.isShow)
              if (ele.goodsKindList.length > 0) {
                ele.goodsKindList.forEach(item => {
                  ele.goodsTypeName.push(item.typeName)
                })
              }
              ele.goodsTypeName = ele.goodsTypeName.join('-')
            })
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    }
  },
  created () {
    this.shopId = this.$route.params.id
    this.getProductList()
    this.getData()
  }
}
</script>

<style lang="less">
#goods_list{
  .search-box .search-item-right {
    width: 20%;
  }
  .search-box .search-item-left{
    width: 80%;
  }
  .vue-treeselect__control{
    height: 33px;
  }
}
</style>
